/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.orogeny.application.compilation;

import org.jetbrains.annotations.NotNull;

import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import static javax.tools.ToolProvider.getSystemJavaCompiler;
import java.io.File;
import java.io.StringWriter;
import static java.lang.String.format;
import static java.lang.System.err;
import java.util.List;
import static java.util.Locale.UK;

public class BuildScriptCompiler
{
	private final File scriptFile;

	public BuildScriptCompiler(final @NotNull File scriptFile)
	{
		this.scriptFile = scriptFile;
	}

	// Need tools.jar on classpath
	@NotNull
	public ClassLoader compileJavaCode()
	{
		final JavaCompiler compiler = getSystemJavaCompiler();
		final DiagnosticCollector<JavaFileObject> compilerErrors = new DiagnosticCollector<JavaFileObject>();
		final InMemoryFileManager manager = new InMemoryFileManager(compiler.getStandardFileManager(compilerErrors, null, null));
		final StringWriter extraInformation = new StringWriter();
		final Boolean succeeded = compiler.getTask(extraInformation, manager, null, null, null, manager.getJavaFileObjectsFromFiles(scriptFile)).call();
		if (!succeeded)
		{
			err.println(extraInformation.toString());
			final List<Diagnostic<? extends JavaFileObject>> diagnostics = compilerErrors.getDiagnostics();
			for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics)
			{
				err.println(diagnostic);
			}
			throw new RuntimeException(format(UK, "Could not compile build script %1$s", scriptFile));
		}
		return manager.getCompiledClassLoader();
	}
}
